package com.ims.client.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class GetDeviceIdUtil {
    public static String getWindowsDeviceId() {

        try {
            String command = "wmic csproduct get UUID";
            StringBuffer output = new StringBuffer();

            Process SerNumProcess = Runtime.getRuntime().exec(command);
            BufferedReader sNumReader = new BufferedReader(new InputStreamReader(SerNumProcess.getInputStream()));

            String line = "";
            while ((line = sNumReader.readLine()) != null) {
                output.append(line + "\n");
            }
            String deviceId = output.toString().substring(output.indexOf("\n"), output.length()).trim();
            ;
            return deviceId;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String getLinuxDeviceId() {
        String deviceId = getAllSerialNumber("hostnamectl", "Machine ID", ": ");
        return deviceId;
    }

    public static String executeLinuxCmd(String cmd) {
        try {
//            System.out.println("got cmd job : " + cmd);
            Runtime run = Runtime.getRuntime();
            Process process;
            process = run.exec(cmd);
            InputStream in = process.getInputStream();
            BufferedReader bs = new BufferedReader(new InputStreamReader(in));
            StringBuffer out = new StringBuffer();
            byte[] b = new byte[8192];
            for (int n; (n = in.read(b)) != -1; ) {
                out.append(new String(b, 0, n));
            }
            in.close();
            process.destroy();
            return out.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getAllSerialNumber(String cmd, String record, String symbol) {
        String execResult = executeLinuxCmd(cmd);
        String[] infos = execResult.split("\n");
        StringBuilder result = new StringBuilder();
        int k = 0;
        for (int i = 0; i < infos.length - 1; i++) {
            String info = infos[i];
            info = info.trim();
            if (info.indexOf(record) != -1) {
                info.replace(" ", "");
                String[] sn = info.split(symbol);
                if (k != 0) {
                    result.append(',');
                }
                result.append(sn[1]);
                k++;
            }
        }
        if (k != 0) {
            return result.toString();
        } else {
            return null;
        }
    }
}
